using OFX.Aggregator.Infrastructure;
using OFX.Aggregator.WebScraping.Infrastructure;

namespace OFX.Aggregator.WebScraping.Implementation.BESnet.HtmlPageProcessing
{
	public class BESnetHomePageProcessor : IHtmlPageProcessor
	{
		#region Implementation of IHtmlPageProcessor

		public void TestAssumptions(StatementSource source, IWebBrowser webBrowser)
		{
			string userName = GetUserName(source);

			if (userName.Length != 7)
				throw new AssumptionFailedException(this, "Username isn't 7-digits long, as expected.");

			IHtmlDocument document = webBrowser.Document;

			IHtmlElement fca = document.GetElementById("fca");
			if (fca == null)
			{
				throw new AssumptionFailedException(this, "Expected 'fca' element not found in page!");
			}
		}

		public void ProcessPage(StatementSource source, IWebBrowser webBrowser, IHtmlPageProcessorFinished finished)
		{
			IHtmlDocument document = webBrowser.Document;

			IHtmlElement fca = document.GetElementById("fca");
			string userName = source.Parameters["AccountUserName"];

			fca.InnerText = userName;
			document.InvokeScript("besx_onkeyup", null);
		}

		#endregion

		private static string GetUserName(StatementSource source)
		{
			return source.Parameters["AccountUserName"];
		}
	}
}